<?php

namespace App\Http\Controllers;

use App\Member;
use App\Http\Requests\MembersRequest;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Validator;

class MemberController extends Controller
{
    public function sendSMS(Request $request, EasySms $easySms)
    {
        if (!$request->phone){
            return response()->json(['error' => '参数错误']);
        }
        $phone = $request->phone;
        // 生成4位随机数，左侧补0
        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

        try {
            $easySms->send($phone, [
                'content'  =>  "【梦途科技】您的验证码是{$code}。如非本人操作，请忽略本短信"
            ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $message = $exception->getException('yunpian')->getMessage();
            return response()->json(['error' => $message]);
        }

        $key = 'verificationCode_'.str_random(15);
        $expiredAt = now()->addMinutes(10);
        // 缓存验证码 10分钟过期。
        \Cache::put($key, ['phone' => $phone, 'code' => $code], $expiredAt);

        return response()->json([
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ]);
    }



    public function store(Request $request, Member $member)
    {
         $validator = Validator::make($request->all(),[
        'openid' => 'required|unique:members',
        'phone' => 'required|unique:members',
        'name' => 'required|min:2',
        'hospital' => 'required|min:3',
        'address'  => 'required',
        'section'  => 'required',
        'job'      => 'required',
        'verification_key' => 'required|string',
        'verification_code' => 'required|string',
    ], [
            'openid.required' => '服务器有误，请重新扫码',
            'openid.unique' => '用户已存在',
            'phone.required' => '未填写手机号',
            'phone.unique' => '手机号已存在',
             'name.required' => '未输入名字',
             'address.required' => '请输入地址',
             'section.required' => '请输入科室',
             'job.required' => '请输入职称',
             'verification_key.required' => '请重新发送验证码(一小时可发三次)',
             'verification_code.required' => '请输入短信验证码'
        ]);

         if ($validator->fails()){
             return response()->json(['error' => $validator->errors()->first()]);
         }

        $verifyData = \Cache::get($request->verification_key);

        if (!$verifyData) {
            return response()->json(['error' => '验证码已失效']);
        }

        if (!hash_equals($verifyData['code'], $request->verification_code)) {
            // 返回401
            return response()->json(['error' => '验证码错误']);
        }
        $member->fill($request->except('verification_key','verification_code'));
        $member->save();

        // 清除验证码缓存
        \Cache::forget($request->verification_key);
        return response()->json()->setStatusCode(201);
    }

    public function check(Request $request, Member $member)
    {
        $data = [
            'is_registered' => false,
            'is_checked'  => false,
        ];
        //判断是否注册
        if (!$request->openid){
            return response()->json(['error' => '缺少必要参数']);
        }
        $one = Member::where('openid', $request->openid)->first();
        if ($one){
            $data['is_registered'] = true;
            //是否已经核销
            $data['is_checked'] = $one->status;
            if ($one->status){
                $data['accepted_at'] = $one->accepted_at;
            }

        }
        return response()->json($data);
    }

    public function accept(Request $request, Member $member)
    {
        if (!$request->openid){
            return response()->json(['error' => '缺少必要参数']);
        }

        $one = Member::where('openid', $request->openid)->first();
        if (!$one){
            return response()->json(['error' => '未找到该用户']);
        }
        if ($one->status){
            return response()->json(['error' => '该卡劵已领过,领取时间:'.$one->accepted_at]);
        }
        $one->status = 1;
        $one->accepted_at = Date('Y-m-d H:i:s', time());
        $one->save();
        return response()->json(['status' => true]);
    }
}
